﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.FoundHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.FoundHouse;
using TomNet.IMSC.Web.Areas.FoundHouse.Models;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.FoundHouse.Controllers
{
    [Description("找房表")]
    public class FoundHouseController : BaseController
    {  
        public IFoundHouseRunningsContract FoundHouseRunningsContract { get; set; }
        public IUsersContract UsersContract { get; set; }
        public IAreaContract AreaContract { get; set; }
        public IFoundHouseRunningsReplyContract FoundHouseRunningsReplyContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public IFoundHouseRunningsReplyBuildingsContract FoundHouseRunningsReplyBuildingsContract { get; set; } 

        #region 找房列表
        [Description("找房-列表")]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult IndexAsync(int pageIndex, int pageSize, string search = "")
        { 
            var query = from fhr in FoundHouseRunningsContract.Entities
                        select new FoundHouseRunningsModel
                        {
                            Id = fhr.Id,
                            UserName = (from u in UsersContract.Entities where u.Id == fhr.UserID select u.Name).FirstOrDefault(), 
                            AreaID = fhr.AreaID,
                            BuildingName = fhr.BuildingName,
                            Use = fhr.Use,
                            HouseType = fhr.HouseType,
                            MinArea = fhr.MinArea,
                            MaxArea = fhr.MinArea,
                            MinPrice = fhr.MinPrice,
                            MaxPrice = fhr.MaxPrice,
                            Remark = fhr.Remark,
                            CreateTime = fhr.CreateTime,
                            State = fhr.State==1?"已回复":"未回复",
                            ReplyCount = (from m in FoundHouseRunningsReplyContract.Entities where fhr.Id == m.FoundHouseRunningsID select m).Count()
                        }; 
             
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.BuildingName.Contains(search));
            }

            var total = query.Count();
            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : query;
            var list = query.ToList();
            foreach (var item in list)
            {
                string[] strArray = item.AreaID.Split(',');
                var area = AreaContract.Entities.Where(m => strArray.Contains(m.Id)).Select(m => m.Name);
                var jkl = string.Join(",", area.ToArray());
                item.AreaID = jkl; 
            }

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = list.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        #region 回复列表
        [Description("回复-列表")]
        public ActionResult ReplyIndex(int FoundHouseRunningsID)
        {
            //登陆人ID
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            ViewBag.agentid = model.Id;
            var entity = FoundHouseRunningsReplyContract.Entities.Where(m=>m.FoundHouseRunningsID == FoundHouseRunningsID).FirstOrDefault();

            //是否有回复
            ViewBag.IsReply = 0;//没有
            if (entity != null)
            {
                ViewBag.IsReply = 1;//存在
            }

            //是否当前客服回复
            ViewBag.IsOwner = 0;//不是本人
            if (entity.StaffID == model.Id)
            {
                ViewBag.IsOwner = 1;//是本人
            }


            ViewBag.FoundHouseRunningsID = FoundHouseRunningsID;
            return View();
        }
        [HttpPost]
        public ActionResult ReplyIndexAsync(int FoundHouseRunningsID,int pageIndex, int pageSize, string search = "")
        {
            var query = from fhrr in FoundHouseRunningsReplyContract.Entities
                        where fhrr.FoundHouseRunningsID == FoundHouseRunningsID
                        select new
                        {
                            Id = fhrr.Id,
                            FoundHouseRunningsID = (from fhr in FoundHouseRunningsContract.Entities where fhrr.FoundHouseRunningsID == fhr.Id select fhr.BuildingName).FirstOrDefault(),
                            StaffID = (from s in StaffContract.Entities where fhrr.StaffID == s.Id select s.Name).FirstOrDefault(),
                            Message = fhrr.Message,
                            CreateTime = fhrr.CreateTime
                        };

            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Message.Contains(search));
            }

            var total = query.Count();
            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : query;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        #region 回复添加
        [Description("回复信息-添加")]
        public ActionResult ReplyInsert(int FoundHouseRunningsID)
        {
            

            ViewBag.FoundHouseRunningsID = FoundHouseRunningsID;
            return View();
        }
        [HttpPost]
        public ActionResult ReplyInsertAsync(int FoundHouseRunningsID, string Message, string LowPriceHouseID)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);

            //开始事务
            FoundHouseRunningsReplyBuildingsContract.Repository.UnitOfWork.BeginTransaction();

            try
            {
                FoundHouseRunningsReply fhrr = new FoundHouseRunningsReply();
                fhrr.FoundHouseRunningsID = FoundHouseRunningsID;
                fhrr.StaffID = model.Id;
                fhrr.Message = Message;
                fhrr.CreateTime = DateTime.Now;
                //添加FoundHouseRunningsReply记录
                var count = FoundHouseRunningsReplyContract.Insert(fhrr);

                var t = LowPriceHouseID.Split(',');
                

                if (LowPriceHouseID!="")
                { 
                    //添加FoundHouseRunningsReplyBuildings记录
                    foreach (string item in LowPriceHouseID.Split(','))
                    {
                        FoundHouseRunningsReplyBuildingsContract.Insert(new FoundHouseRunningsReplyBuildings { FoundHouseRunningsReplyID = fhrr.Id, LowPriceHouseID = Convert.ToInt32(item) });
                    }
                }

                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "录入成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "录入失败";
                }
            }
            catch (Exception e)
            { 

                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
                //事务回滚
                FoundHouseRunningsReplyBuildingsContract.Repository.UnitOfWork.Rollback();
            }

            //结束事务
            FoundHouseRunningsReplyBuildingsContract.Repository.UnitOfWork.Commit();

            return JsonEx(result);
        }
        #endregion

        #region 回复修改
        [Description("回复信息-修改")]
        public ActionResult ReplyEdit(int id)
        { 
            var entity = FoundHouseRunningsReplyContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewBag.entity = entity;
            var lentity = FoundHouseRunningsReplyBuildingsContract.Entities.Where(m => m.FoundHouseRunningsReplyID == id);
            //低价房id集合
            string LowPriceHouseID = string.Join(",", lentity.Select(m => m.LowPriceHouseID).ToList());
            ViewBag.LowPriceHouseID = LowPriceHouseID;
            return View();
        }
        [HttpPost]
        public ActionResult ReplyEditListAsync(int FoundHouseRunningsID, string Message, string LowPriceHouseID,int id)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                FoundHouseRunningsReply fhrr = new FoundHouseRunningsReply();
                fhrr.Id = id;
                fhrr.FoundHouseRunningsID = FoundHouseRunningsID;
                fhrr.StaffID = model.Id;
                fhrr.Message = Message;
                fhrr.CreateTime = DateTime.Now;

                //删除添加FoundHouseRunningsReplyBuildings原有记录
                var entity = FoundHouseRunningsReplyBuildingsContract.Entities.Where(m => m.FoundHouseRunningsReplyID ==fhrr.Id).ToList();
                foreach (var item in entity)
                {
                    FoundHouseRunningsReplyBuildingsContract.DeleteDirect(item.Id);
                }


                if (LowPriceHouseID != "")
                {
                    //添加FoundHouseRunningsReplyBuildings记录
                    foreach (string item in LowPriceHouseID.Split(','))
                    {
                        FoundHouseRunningsReplyBuildingsContract.Insert(new FoundHouseRunningsReplyBuildings { FoundHouseRunningsReplyID = fhrr.Id, LowPriceHouseID = Convert.ToInt32(item) });
                    }
                }


                //添加FoundHouseRunningsReply记录
                var count = FoundHouseRunningsReplyContract.Update(fhrr);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch(Exception e)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 回复删除
        [Description("回复信息-删除")]
        [HttpPost]
        public ActionResult ReplyDeleteListAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                foreach (var item in idsInt)
                {
                    FoundHouseRunningsReplyContract.DeleteDirect(item);
                }

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion 

        public void Area(string Areaid)
        {
            var id = Areaid.Split(',');
            foreach (var item in id)
            {
                var entity = AreaContract.Entities.Where(m=>m.Id == Areaid);

            }
            
        }

    }
}